package cn.chen.controller;

import cn.chen.model.Order;
import cn.chen.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hbpu
 * @since 2023-05-27
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    //增
    @PostMapping("/add")
    public boolean addOrder(@RequestBody Order order){
        //根据uid和gid查询是否已经购买过
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUid,order.getUid());
        wrapper.eq(Order::getGid,order.getGid());
        Order one = orderService.getOne(wrapper);
        if(one!=null){
            return false;
        }
        //填充时间
        order.setCreateTime(String.valueOf(LocalDateTime.now()));
        return orderService.save(order);
    }

    //删
    @GetMapping("/delete")
    public boolean deleteOrder(Order order){
        return orderService.removeById(order);
    }

    //改
    @PostMapping("/update")
    public boolean updateOrder(@RequestBody  Order order){
        return orderService.updateById(order);
    }

    //查
    @GetMapping("/get")
    public Order getOrder(Order order){
        return orderService.getById(order);
    }

    //查所有
    @GetMapping("/getAll")
    public List<Order> getAllOrder(Integer page, Integer size, Integer uid){
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUid,uid);
        return orderService.page(new Page<>(page,size),wrapper).getRecords();
    }


}
